package cn.chenfeifx.core.controls.skins;

import cn.chenfeifx.core.common.FxUtil;
import cn.chenfeifx.core.controls.CFDirectoryChooser;
import cn.chenfeifx.core.controls.CFTextField;
import javafx.scene.control.SkinBase;
import javafx.stage.FileChooser;
import org.kordamp.ikonli.antdesignicons.AntDesignIconsOutlined;
import org.kordamp.ikonli.javafx.FontIcon;

import java.io.File;

public class CFFileChooserSkin extends SkinBase<CFDirectoryChooser> {

    private final FileChooser fileChooser;
    private final CFTextField cfTextField;

    public CFFileChooserSkin(CFDirectoryChooser control) {
        super(control);
        fileChooser = new FileChooser();
        cfTextField = new CFTextField();
        cfTextField.setSuffixIcon(FontIcon.of(AntDesignIconsOutlined.FILE));
        cfTextField.setEditable(false);
        cfTextField.setClearable(true);
        cfTextField.setPromptText("选择文件");
        getChildren().add(cfTextField);
        //
        initEvent(control);
    }

    private void initEvent(CFDirectoryChooser control) {
        cfTextField.setSuffixIconOnMouseClicked(event -> {
            File file = fileChooser.showOpenDialog(FxUtil.getWindow(cfTextField));
            control.fileProperty().set(file);
            cfTextField.setText(file == null ? "" : file.getPath());
        });
        cfTextField.textProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == null || newValue.isEmpty()) {
                control.fileProperty().set(null);
            }
        });
    }

    @Override
    protected void layoutChildren(double contentX, double contentY, double contentWidth, double contentHeight) {
        super.layoutChildren(contentX, contentY, contentWidth, contentHeight);
    }
}
